#include "ConfigFile.h"

ConfigFile::ConfigFile(string filename) {
    ifstream cf(filename.c_str());

    if (!cf.good()) throw "Could not open config file.";
        
    string line;
    string section;
    string name;
    string value;
    string::size_type posEqual;

    while(getline(cf, line)) {
        // If line is empty or commented, skip it
        if (!line.length()) continue;
        if (line[0] == '#') continue;
        if (line[0] == ';') continue;

        // New section
        if (line[0] == '[') {
            section = line.substr(1, line.find(']') - 1);
            sections.push_back(section);
            continue;
        }

        posEqual = line.find('=');
        name     = line.substr(0, posEqual);
        value    = line.substr(posEqual + 1);

        content[section + '/' + name] = Chameleon(value);
    }

    cf.close();
}

Chameleon ConfigFile::getValue(string section, string name) {
    map<string, Chameleon>::iterator i = content.find(section + '/' + name);

    if (i == content.end()) throw "Does not exist!";

    return i->second;
}

vector<string> ConfigFile::getSections() {
    return sections;
}
